import json
import uuid
from datetime import datetime

import pika

from credit_voice_service.settings import MQ_CONFIG


class RabbitMQSender:
    def __init__(self, host, port, username, password, vhost, queue_name):
        self.credentials = pika.PlainCredentials(username, password)
        self.parameters = pika.ConnectionParameters(host=host, port=port, virtual_host=vhost,
                                                    credentials=self.credentials)
        self.queue_name = queue_name
        self.connection = None
        self.channel = None

    def connect(self):
        self.connection = pika.BlockingConnection(self.parameters)
        self.channel = self.connection.channel()
        self.channel.queue_declare(queue=self.queue_name)

    def publish(self, exchange, routing_key, message):
        message_id = str(uuid.uuid4())
        self.channel.basic_publish(exchange=exchange, routing_key=routing_key, body=message,
                                   properties=pika.BasicProperties(message_id=message_id))

    def close(self):
        if self.connection.is_open:
            self.connection.close()


if __name__ == '__main__':
    sender = RabbitMQSender(username=MQ_CONFIG.get("username"), password=MQ_CONFIG.get("password"),
                            host=MQ_CONFIG.get("hostname"), port=MQ_CONFIG.get("port"),
                            vhost=MQ_CONFIG.get("vhost"), queue_name=MQ_CONFIG.get("queue"))
    sender.connect()
    message = {
        "msgContent": "测试数据4",
        "workspaceId": 55369,
        "speakerType": "IVR",
        "sessionId": "0-2120-671322255-1667158375230459904-490",
        "msgTime": datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
    }
    sender.publish("dm_record", "dm_record", json.dumps(message))
    sender.close()
    pass